package com.devbobcorn.nekoration.blocks.entities;

import javax.annotation.Nullable;

import com.devbobcorn.nekoration.utils.TagTypes;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

public class PhonographBlockEntity extends TileEntity {
    public Integer type = 0;
	public Byte dir = 0;
	public int[] offset = { 0, 0, 0 };
	public int[] colors = { 0xFFFFFF, 0x00FFFF }; // RGB Color, by default white and cyan...
	public double scale = 1.0;
	public Integer line = -1;

    public PhonographBlockEntity() {
        super(ModTileEntityType.PHONOGRAPH_TYPE.get());
    }

    public CompoundNBT save(CompoundNBT tag){
        super.save(tag); // The super call is required to save the tile's location
		tag.putInt("Type", type);
		tag.putByte("Dir", dir);
		tag.putIntArray("Offset", offset);
		tag.putIntArray("Colors", colors);
		tag.putDouble("Scale", scale);
		tag.putInt("Line", line);
        return tag;
    }

    public void load(BlockState state, CompoundNBT tag) {
        super.load(state, tag);
		if (tag.contains("Model", TagTypes.INT_NBT_ID)) {
			type = tag.getInt("Model");
		}
		if (tag.contains("Dir", TagTypes.BYTE_NBT_ID)) {
			dir = tag.getByte("Dir");
		}
		if (tag.contains("Offset", TagTypes.INT_ARRAY_NBT_ID)) {
			offset = tag.getIntArray("Offset");
		}
		if (tag.contains("Colors", TagTypes.INT_ARRAY_NBT_ID)) {
			colors = tag.getIntArray("Colors");
		}
		if (tag.contains("Scale", TagTypes.DOUBLE_NBT_ID)) {
			scale = tag.getDouble("Scale");
		}
		if (tag.contains("Line", TagTypes.INT_NBT_ID)) {
			line = tag.getInt("Line");
		}
    }

    @Nullable
	public SUpdateTileEntityPacket getUpdatePacket() {
		return new SUpdateTileEntityPacket(this.worldPosition, 1202, this.getUpdateTag());
	}

	public CompoundNBT getUpdateTag() {
		return this.save(new CompoundNBT());
	}
    
	@Override
	public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
		BlockState blockState = level.getBlockState(worldPosition);
		load(blockState, pkt.getTag()); // read from the nbt in the packet
	}

	@OnlyIn(Dist.CLIENT)
	public double getViewDistance() {
	   return 4096.0D;
	}

    @OnlyIn(Dist.CLIENT)
    public boolean shouldRenderFace(Direction dir) {
        return Block.shouldRenderFace(this.getBlockState(), this.level, this.getBlockPos(), dir);
    }
}
